import signal
import sys
from concurrent import futures
import grpc
from loguru import logger

# from config import BASE_DIR
from blog.handlers.blog import BlogService
from blog.proto import blog_pb2_grpc
from configs.config import BASE_DIR
from configs import config

logger.add(sink=f"{BASE_DIR}/logs/blog.log", rotation='00:00', enqueue=True)


class LogInterceptor(grpc.ServerInterceptor):
    def intercept_service(self, continuation, handler_call_details):
        print('start...')
        print(type(handler_call_details))
        rsp = continuation(handler_call_details)
        print('end...')
        return rsp


def on_exit(signo, frame):
    logger.info(f'signal terminal, signal num: {signo}, frame: {frame}')
    sys.exit(0)


def init():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=(LogInterceptor(),))
    blog_pb2_grpc.add_BlogServiceServicer_to_server(BlogService(), server)
    server.add_insecure_port(f"{config.SERVER_HOST}:{config.SERVER_PORT}")
    logger.info(f'server start, listen {config.SERVER_PORT}...')

    signal.signal(signal.SIGINT, on_exit)
    signal.signal(signal.SIGTERM, on_exit)

    server.start()
    # 等待结束
    server.wait_for_termination()


if __name__ == '__main__':
    init()
